<?php

namespace App\Http\Requests;

// use Illuminate\Contracts\Validation\Validator;
// use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use App\Common\Helper;
use App\Common\Http\Result;
// use App\Common\Enum\{TrueCode,ResultMsg};
use App\Common\Http\Basics\Error;
use App\Common\Http\Basics\Success;
use Pearl\RequestValidate\RequestAbstract;

// use Illuminate\Contracts\Validation\Factory as ValidationFactory;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Arr;


class Request extends RequestAbstract
{


    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Http\Exceptions\HttpResponseException
     */
    protected function failedValidation(Validator $validator) :ValidationException
    {
        // throw new HttpResponseException( Helper::toHttpJson(Http::FAIL,'表单验证错误',$validator->getMessageBag()->toArray(),TrueCode::DATA_ERROR));

        $result = new Result( $validator->getMessageBag()->toArray(), Error::FORM_VAILD_ERROR);
        throw new HttpResponseException( Helper::toHttpJson($result) );
    }




    public  function rules()
    {
        $action = Arr::last(explode('@',$this->route()[1]['uses']));
        if(  !method_exists($this,'scene')  ) return [];
        $scene =   $this->scene()[ $action ] ??   [];  //场景的规则和控制器的方法有关
        if(empty($scene)) return   [];
        $common =  $this->rule ?? [];    //公共规则
        $newRule = [];
        foreach($scene as $key =>  $val){
            if(is_string($val) && isset($common[$val]) )  $newRule[$val] =  $common[$val];
            else $newRule[$key] = $val;
        }
        return  $newRule;
    }

}
